package online.inote.naruto.common.utils.i18n;

import org.springframework.context.i18n.LocaleContextHolder;

import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @description 国际化语言
 * @author gaopengsui@creditease.cn
 * @date 2021/09/08 11:42
 */
public class I18n {

  public static volatile Map<String, ResourceBundle> RESOURCE_BUNDLE_MAP =
      new ConcurrentHashMap<>();

  /**
   * 获取对应语言的文本，当资源文件或key不存在时，直接返回 {@code MessageFormat.format(key, args)}
   *
   * @param bundleName 资源文件名
   * @param key 字符串key
   * @return 格式化文本
   */
  public static String message(String bundleName, String key) {

    ResourceBundle bundle = bundle(bundleName);

    if (bundle == null) {
      return key;
    }

    try {
      return bundle.getString(key);
    } catch (MissingResourceException e) {
      return key;
    }
  }

  public static ResourceBundle bundle(String bundleName) {
    Locale locale = LocaleContextHolder.getLocale();
    String languageBundleName = bundleName + locale.getLanguage() + locale.getCountry();

    if (!RESOURCE_BUNDLE_MAP.containsKey(languageBundleName)) {
      synchronized (RESOURCE_BUNDLE_MAP) {
        if (!RESOURCE_BUNDLE_MAP.containsKey(languageBundleName)) {
          RESOURCE_BUNDLE_MAP.put(languageBundleName, ResourceBundle.getBundle(bundleName, locale));
        }
      }
    }

    return RESOURCE_BUNDLE_MAP.get(languageBundleName);
  }
}
